import type { Directive } from "@vue/runtime-core";
import timeFormat from "../plugins/newTimeFormat"

const time: Directive = {
  beforeMount(el, binding): void {
    if (binding.value) {
      const time: timeFormat = new timeFormat(binding.value, binding.modifiers.show ? true : false);
      el.innerHTML = time.getFormatTime();
      const date: Date = new Date();
      // 第二天凌晨时间
      const nextZero: Date = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1, 0, 0, 0);
      // 两者相隔的毫秒数
      const timestamp: number = nextZero.getTime() - date.getTime();
      el.__vueTime__ = setInterval(() => {
        el.innerHTML = time.getFormatTime();
        // 清除定时器
        clearInterval(el.__vueTime__);

        // 以后每天的凌晨进行更新
        el.__vueTime__ = setInterval(() => el.innerHTML = time.getFormatTime(), 86400000);
      }, timestamp);
    }
  },
  beforeUnmount(el): void {
    clearInterval(el.__vueTime__);
    Reflect.deleteProperty(el, '.__vueTime__');
  },
};

export default time